package dp.mobile.eden;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;

import dp.mobile.comm.ICommHandler;
import dp.mobile.comm.worker.BluetoothHandler;
import dp.mobile.entity.saveable.SaveablePlayer;
import dp.mobile.system.SoundManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;

public class GameOverAct extends Activity implements ICommHandler {
	private static final int REQUEST_PLAYER_STAT_ID = 200;
	private static final int PLAYER_STAT_ID = 201;
	
	private static final int MSG_WHAT_PLAYER_STAT = 301;
	private SaveablePlayer mPlayerStat;
	private boolean isReplied = false;
	
	public static final String EXTRA_SKIRMISH = "SKIRMISH";
	public static final String EXTRA_CAMPAIGN = "CAMPAIGN";
	public static final String EXTRA_MULTIPLAYER = "MULTIPLAYER";
	public static final String EXTRA_LEVEL_SOURCE = "LEVEL_SOURCE";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_over);
		BluetoothHandler.getInstance().setEventHandler(this);
		
		initComp();
		if (getIntent().getExtras().getBoolean(EXTRA_MULTIPLAYER, false)) {
			mRetryBtn.setVisibility(View.GONE);
		}
		
		setListener();
		startAnimation();
		
		if (getIntent().getExtras() != null) {
			SaveablePlayer p = (SaveablePlayer)getIntent().getSerializableExtra(GameActivityBase.EXTRA_PLAYER_STAT);
			mPlayerStat = p;
			mP1Score.setText(p.mScore + "");
			mP1Elect.setText(p.mElectricity + "");
			mP1Bonus.setText(p.mBonus + "");
			if (p.mLife <= 0)
				mP1Name.setText(BluetoothHandler.getInstance().getAdapter().getName() + " (Loser)");
			else
				mP1Name.setText(BluetoothHandler.getInstance().getAdapter().getName() + " (Winner)");
		}
		else {
			mP1Score.setVisibility(View.GONE);
			mP1Elect.setVisibility(View.GONE);
			mP1Bonus.setVisibility(View.GONE);
			mP1Name.setVisibility(View.GONE);
			
			mP2Score.setVisibility(View.GONE);
			mP2Elect.setVisibility(View.GONE);
			mP2Bonus.setVisibility(View.GONE);
			mP2Name.setVisibility(View.GONE);
		}
		
		mP2Score.setVisibility(View.GONE);
		mP2Elect.setVisibility(View.GONE);
		mP2Bonus.setVisibility(View.GONE);
		mP2Name.setVisibility(View.GONE);
		
		Thread t = new Thread() {
			@Override
			public void run() {
				while (!isReplied) {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					Log.i("this" , "SENDING REQUEST");
					BluetoothHandler.getInstance().sendObjectId(REQUEST_PLAYER_STAT_ID);
				}
			}
		};
		
		//t.start();
		//BluetoothHandler.getInstance().sendObjectId(REQUEST_PLAYER_STAT_ID);
	}
	
	private void initComp(){
		mRetryBtn		= (Button) findViewById(R.id.retry_btn);
		mMainMenuBtn	= (Button) findViewById(R.id.main_menu_btn);
		
		mRetryBtnAnim		= AnimationUtils.loadAnimation(this, R.anim.left_to_right);
		mMainMenuBtnAnim	= AnimationUtils.loadAnimation(this, R.anim.right_to_left);
		
		//Stats Table
		mStatsTable		= (TableLayout) findViewById(R.id.stats_table);
		
		mP1Score		= (TextView) findViewById(R.id.p1_score);
		mP1Elect		= (TextView) findViewById(R.id.p1_elect);
		mP1Bonus		= (TextView) findViewById(R.id.p1_bonus);
		mP1Name			= (TextView) findViewById(R.id.p1_name);
		
		mP2Score		= (TextView) findViewById(R.id.p2_score);
		mP2Elect		= (TextView) findViewById(R.id.p2_elect);
		mP2Bonus		= (TextView) findViewById(R.id.p2_bonus);
		mP2Name			= (TextView) findViewById(R.id.p2_name);
	}
	
	private void setListener(){
		mMainMenuBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		mRetryBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (getIntent().getExtras().getBoolean(EXTRA_SKIRMISH, false)) {
					Intent intent = new Intent(GameOverAct.this.getApplicationContext(), SkirmishAct.class);
					intent.putExtra("level", getIntent().getExtras().getString(EXTRA_LEVEL_SOURCE));
					startActivity(intent);
				}
				else if (getIntent().getExtras().getBoolean(EXTRA_CAMPAIGN, false)) {
					Intent intent = new Intent(GameOverAct.this.getApplicationContext(), CampaignAct.class);
					intent.putExtra("level", getIntent().getExtras().getString(EXTRA_LEVEL_SOURCE));
					startActivity(intent);
				} 
				
				finish();
			}
		});
	}
	
	private void startAnimation(){
		mRetryBtn.startAnimation(mRetryBtnAnim);
		mMainMenuBtn.startAnimation(mMainMenuBtnAnim);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		SoundManager.instance(getBaseContext()).temporarySetMute(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SoundManager.instance(getBaseContext()).temporarySetMute(false);
	}
	
	RelativeLayout	mGameOverLayout;
	Button			mRetryBtn, mMainMenuBtn;
	Animation		mRetryBtnAnim, mMainMenuBtnAnim;
	
	//Stats Table
	private TableLayout	mStatsTable;
	private TextView	mP1Score, mP1Elect, mP1Bonus, mP1Name;
	private TextView	mP2Score, mP2Elect, mP2Bonus , mP2Name;
	
	@Override
	public void onAcceptFailed() {}

	@Override
	public void onConnectFailed() {}

	@Override
	public void onConnected() {}

	@Override
	public void onConnectionFailed() {}
	
	private SaveablePlayer mOpponentStat;
	
	private Handler mHandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MSG_WHAT_PLAYER_STAT) {
				mP2Score.setVisibility(View.VISIBLE);
				mP2Elect.setVisibility(View.VISIBLE);
				mP2Bonus.setVisibility(View.VISIBLE);
				mP2Name.setVisibility(View.VISIBLE);
				
				mP2Name.setText(BluetoothHandler.getInstance().getConnectedDevice().getName());
				mP2Score.setText(mOpponentStat.mScore + "");
				mP2Elect.setText(mOpponentStat.mElectricity + "");
				mP2Bonus.setText(mOpponentStat.mBonus + "");
				isReplied = true;
			}
		};
	};

	@Override
	public void onObjectReceived(int objId, ObjectInputStream is) {
		if (objId == REQUEST_PLAYER_STAT_ID) {
			BluetoothHandler.getInstance().sendObjectId(PLAYER_STAT_ID);
			BluetoothHandler.getInstance().send(mPlayerStat);
		}
		else if (objId == PLAYER_STAT_ID) {
			Message m = new Message();
			m.what = MSG_WHAT_PLAYER_STAT;
			try {
				mOpponentStat = (SaveablePlayer) is.readObject();
			} catch (OptionalDataException e) {
			} catch (ClassNotFoundException e) {
			} catch (IOException e) {
			}
			mHandler.sendMessage(m);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		BluetoothHandler.getInstance().disconnect();
	}
}
